"use client";

import React, { useEffect, useState } from "react";
import { system } from "@/forent-api/api";
import { Form, FormProps, App } from "antd";
import { useRouter } from "next/navigation";
import useStore from "@/store/store";
import ParticleBackground from "@/components/ParticleBackground";
import { LoginCard, LoginCardProps } from "@/components/LoginCard";
import { initSysDict, initRBAC } from "../gloableTools";

type FieldType = {
  username?: string;
  password?: string;
  remember?: boolean;
};

export default function LoginPage() {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const { message } = App.useApp();
  const router = useRouter(); // 使用 useRouter

  useEffect(() => {
    localStorage.removeItem("sys_user");
    localStorage.removeItem("token");
    localStorage.removeItem("user_menus"); // 清除菜单缓存
    useStore.dispatch({
      type: "LOGOUT",
      payload: { user: null, isLoggedIn: false },
    });
  }, []);

  const onFinish: FormProps<FieldType>["onFinish"] = async (values) => {
    try {
      setLoading(true);
      const res = await system.login(values);
      if (res.code === 200) {
        await localStorage.setItem("token", res.data.token); // 保存 token
        await initSysDict();
        await initRBAC(); // 初始化RBAC系统
        await getUserInfoAction(values);
      } else {
        message.error(res.msg);
      }
    } catch (error) {
      console.error("Login error:", error);
      message.error("登录失败");
    } finally {
      setLoading(false);
    }
  };

  // 获取首个可用菜单路径
  const getFirstAvailableMenuPath = async (userData: any) => {
    // 超级管理员使用固定路径
    if (userData.user_type === "00") {
      return `/agent/system/home`;
    }
    
    try {
      // 为非超级管理员获取动态菜单
      const response = await system.getUserMenu({
        userType: userData.user_type,
        roleType: userData.role_type || ''
      });
      
      // 如果获取到菜单数据
      if (response?.data?.data && response.data.data.length > 0) {
        const menuData = response.data.data;
        
        // 查找第一个可用菜单项的路径
        const findFirstMenuPath = (items: any[]): string | null => {
          // 先遍历顶级菜单
          for (const item of items) {
            if (item.menu_path && item.visible && item.status === 1) {
              return item.menu_path;
            }
          }
          
          // 再遍历子菜单
          for (const item of items) {
            if (item.children && item.children.length > 0) {
              const childPath = findFirstMenuPath(item.children);
              if (childPath) return childPath;
            }
          }
          
          return null;
        };
        
        const menuPath = findFirstMenuPath(menuData);
        if (menuPath) {
          return menuPath;
        }
      }
      
      // 如果没有找到菜单，使用默认路径
      return `/agent/main/home`;
    } catch (error) {
      console.error("获取菜单失败:", error);
      // 出错时使用默认路径
      return `/agent/main/home`;
    }
  };

  // 获取用户信息
  const getUserInfoAction = async (inputValues: any) => {
    const userInfoResponse = await system.getUserInfo({});
    const userData = userInfoResponse.data;
    const isRemember = inputValues.remember;
    console.log("userData", userData);
    if (userData) {
      localStorage.setItem("sys_user", JSON.stringify(userData));
      localStorage.setItem("user_type", userData.user_type);
      localStorage.setItem("mq_routing_key", userData.deptInfo.mq_routing_key);
      localStorage.setItem("dept_id", userData.deptInfo.dept_id);
      if (isRemember) {
        localStorage.setItem("remember", "true");
        localStorage.setItem("user_name", inputValues.user_name);
        localStorage.setItem("password", inputValues.password);
      } else {
        localStorage.setItem("remember", "false");
        localStorage.removeItem("user_name");
        localStorage.removeItem("password");
      }

      // 先更新store状态
      useStore.dispatch({
        type: "LOGIN_SUCCESS",
        payload: { user: userData },
      });
      
      // 获取菜单并确定跳转路径
      try {
        const redirectPath = await getFirstAvailableMenuPath(userData);
        
        // 确保store更新后再跳转
        setTimeout(() => {
          router.push(redirectPath);
        }, 100);
      } catch (error) {
        console.error("跳转失败:", error);
        // 出错时使用默认路径
        setTimeout(() => {
          if (userData.user_type === "00") {
            router.push(`/agent/system/home`);
          } else {
            router.push(`/agent/main/home`);
          }
        }, 100);
      }
    } else {
      message.error(userInfoResponse.msg);
    }
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    // console.log("Failed:", errorInfo);
  };

  return (
    <div className="h-screen w-screen flex items-center justify-center bg-gradient-to-br from-gray-900 via-purple-900 to-violet-800 relative overflow-hidden">
      {/* 粒子动画和机器人 */}
      <ParticleBackground />

      {/* 登录卡片 */}
      <LoginCard
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        loading={loading}
        form={form}
      />
    </div>
  );
}
